from fastapi import APIRouter, UploadFile, File
from fastapi.responses import JSONResponse
from pathlib import Path
from pydantic import BaseModel
from typing import Optional
from paddleocr import PaddleOCR
from PIL import Image, ImageFilter
import base64
import io
import time
import numpy as np
from method import Log

router = APIRouter(default_response_class=JSONResponse)

# 定义图片存储路径
UPLOAD_DIR = Path("static/uploads")
# 创建目录（如果不存在）
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
# 'ch' = 中文；'en' 英文；'ch' 会自动包含英文
ocr = PaddleOCR(use_angle_cls=True, lang='ch')

@router.post('/file')
async def upload_file(file: UploadFile = File(...)):
    try:
        result_text = []
        file_data = await file.read()  # 异步读取二进制数据
        # 保存路径
        # 2. 生成基于时间戳的文件名（格式：timestamp_随机数.扩展名）
        # timestamp = int(time.time() * 1000)
        # file_ext = file.filename.split('.')[-1]
        # new_filename = f"{timestamp}.{file_ext}"
        # file_path = UPLOAD_DIR / new_filename
        # with file_path.open("wb") as f:
        #     f.write(file_data)
        # await file.close()  # 显式关闭文件
        img = Image.open(io.BytesIO(file_data))

        # 灰度处理 + 锐化
        img = img.convert('RGB')
        # img = img.filter(ImageFilter.SHARPEN)
        # 识别图像
        result = ocr.ocr(np.array(img))
        # 输出文字结果
        for page in result:
            rec_texts = page.get("rec_texts", [])
            rec_scores = page.get("rec_scores", [])
            for text, score in zip(rec_texts, rec_scores):
                if score > 0.89:
                    result_text.append(text)
        return {
            "list": result_text
        }
    except Exception as e:
        Log.set_log(f"图片识别失败: {e}", 'file')

class Postbase64(BaseModel):
    url: Optional[str] = ''
@router.post('/examine/img')
def discern_img(post: Postbase64):
    # 如果是带前缀的，如 ""，先去掉前缀
    if ',' in post.url:
        post.url = post.url.split(',')[1]

    binary_data = base64.b64decode(post.url)
    result_text = []

    img = Image.open(io.BytesIO(binary_data))

    # 灰度处理 + 锐化
    img = img.convert('RGB')
    # img = img.filter(ImageFilter.SHARPEN)
    # 识别图像
    result = ocr.ocr(np.array(img))
    # 输出文字结果
    for page in result:
        rec_texts = page.get("rec_texts", [])
        rec_scores = page.get("rec_scores", [])
        for text, score in zip(rec_texts, rec_scores):
            if score > 0.89:
                result_text.append(text)
    return {
        "list": result_text
    }
